package com.music.web.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.music.biz.UserBiz;
import com.music.biz.UserRoleBiz;
import com.music.entity.User;
import com.music.entity.UserRole;

@Controller
public class UserController {
	@Autowired
	private UserBiz userBiz;
	@Autowired
	private UserRoleBiz userRoleBiz;

	@RequestMapping("login")
	public String login() {
		return "login";
	}

	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
	public String doLogin(String username, String password,
			HttpSession session, String returnUrl, Model model) {
		User user = userBiz.checkLogin(username, password);
		if (user != null) {// 登陆成功
			session.setAttribute("user", user);
			if (returnUrl != null) {
				return "redirect:" + returnUrl;
			} else {
				return "redirect:index";
			}
		} else {
			model.addAttribute("error", "用户名或者密码错误");
			return "login";
		}
	}

	@RequestMapping("register")
	public String doRegister() {
		return "register";
	}

	@RequestMapping(value = "/registers", method = RequestMethod.POST)
	public String Register(User user, Model model, HttpSession session) {
		List<UserRole> userRoles = userRoleBiz.getAll();
		User users = user;
		users.setUserRole(userRoles.get(0));
		try {
			userBiz.register(users);
			session.setAttribute("user", users);
			return "redirect:index";// 重定向首页
		} catch (Exception e) {
			model.addAttribute("error", e);
		}
		return "register";

	}

	// 检查用户名是否重复
	@RequestMapping("check")
	public void checkname(String username, HttpServletResponse response) {
		int count = userBiz.checkUsername(username).size();
		// 获得输出流，将结果写入流中
		try {

			response.getWriter().print(count > 0);
			System.out.println(count);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
